package com.hoku.account.service;

import com.hoku.account.client.IAuthClient;
import com.hoku.account.dao.IAccountDao;
import com.hoku.account.model.Account;
import com.hoku.account.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao dao;

    @Autowired
    private IAuthClient authClient;

    @Override
    public Account findByName(String accountName) {
        Assert.hasLength(accountName, "account name must be valid!");
        return this.dao.findByName(accountName);
    }

    @Override
    public Account create(User user) {
        Account existing = this.dao.findByName(user.getUsername());
        Assert.isNull(existing, "account already exists: " + user.getUsername());

        Account account = new Account();
        account.setName(user.getUsername());

        this.authClient.createUser(user);

        this.dao.save(account);
        log.info("account {} create success!", account.getName());
        return account;
    }

    @Override
    public void saveChanges(String name, Account update) {
        Account account = this.dao.findByName(name);
        Assert.notNull(account, "can't find account with name " + name);
        this.dao.save(update);
        log.debug("account {} changes has been saved", name);
    }
}
